package com.molyfun.core.util;



import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HttpContext;
import org.apache.commons.codec.binary.Base64;
import org.springframework.context.annotation.PropertySource;

import com.molyfun.core.support.mq.listener.NotifyMessageProducer;
import com.molyfun.core.support.mq.vo.Sms;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.zip.GZIPInputStream;

@PropertySource(value = { "classpath:config/sms.properties" })
public class SmsUtil {

	public static final ResourceBundle SMS = ResourceBundle.getBundle("config/sms");

	/**
	 * 消息发送前准备,检查手机号是否为空,拼装短信信息
	 */
	public static void sendNotifyPrepare(String phone,String smsContent,NotifyMessageProducer notifyProducer)
	{
		if("0".equals(SMS.getString("sms_switch")))
		{
			return;
		}
		Sms s = new Sms(phone,smsContent);
		sendNotifyMessage(s,notifyProducer);
	}

	/**
	 * 发送用户变更消息.
	 * 
	 * 同时发送只有一个消费者的Queue消息与发布订阅模式有多个消费者的Topic消息.
	 */
	private static void sendNotifyMessage(Sms sms,NotifyMessageProducer notifyProducer) {
		if (notifyProducer != null) {
			try {
				notifyProducer.sendQueue(sms);
			} catch (Exception e) {
			}
		}
	}


	public static String sendSms(Sms sms) throws Exception {

		DefaultHttpClient client = new DefaultHttpClient();

		client.addRequestInterceptor(new HttpRequestInterceptor() {
			@Override
			public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
				request.addHeader("Accept-Encoding", "gzip");
				request.addHeader("Authorization", "Basic " + new Base64().encodeToString(SMS.getString("api_key").getBytes("utf-8")));
			}
		});

		client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);

		HttpPost request = new HttpPost(SMS.getString("sms.url"));

		ByteArrayOutputStream bos = null;
		InputStream bis = null;
		byte[] buf = new byte[10240];

		String content = null;
		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("mobile", sms.getPhone()));
			params.add(new BasicNameValuePair("message", sms.getContent()+"【你好】"));
			request.setEntity(new UrlEncodedFormEntity(params, "utf-8"));


			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				bis = response.getEntity().getContent();
				Header[] gzip = response.getHeaders("Content-Encoding");

				bos = new ByteArrayOutputStream();
				int count;
				while ((count = bis.read(buf)) != -1) {
					bos.write(buf, 0, count);
				}
				bis.close();

				if (gzip.length > 0 && gzip[0].getValue().equalsIgnoreCase("gzip")) {
					GZIPInputStream gzin = new GZIPInputStream(new ByteArrayInputStream(bos.toByteArray()));
					StringBuffer sb = new StringBuffer();
					int size;
					while ((size = gzin.read(buf)) != -1) {
						sb.append(new String(buf, 0, size, "utf-8"));
					}
					gzin.close();
					bos.close();

					content = sb.toString();
				} else {
					content = bos.toString();
				}

				System.out.println(content);
			} else {
				System.out.println("error code is " + response.getStatusLine().getStatusCode());
			}
			return content;

		} finally {
			if (bis != null) {
				try {
					bis.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
				}
			}
		}
	}

	private String testStatus() throws Exception {

		DefaultHttpClient client = new DefaultHttpClient();

		client.addRequestInterceptor(new HttpRequestInterceptor() {
			@Override
			public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
				request.addHeader("Accept-Encoding", "gzip");
				request.addHeader("Authorization", "Basic " + new Base64().encodeToString(SMS.getString("api_key_status").getBytes("utf-8")));
			}
		});

		client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
		client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);

		HttpGet request = new HttpGet(SMS.getString("status.url"));

		ByteArrayOutputStream bos = null;
		InputStream bis = null;
		byte[] buf = new byte[10240];

		String content = null;
		try {
			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				bis = response.getEntity().getContent();
				Header[] gzip = response.getHeaders("Content-Encoding");

				bos = new ByteArrayOutputStream();
				int count;
				while ((count = bis.read(buf)) != -1) {
					bos.write(buf, 0, count);
				}
				bis.close();

				if (gzip.length > 0 && gzip[0].getValue().equalsIgnoreCase("gzip")) {
					GZIPInputStream gzin = new GZIPInputStream(new ByteArrayInputStream(bos.toByteArray()));
					StringBuffer sb = new StringBuffer();
					int size;
					while ((size = gzin.read(buf)) != -1) {
						sb.append(new String(buf, 0, size, "utf-8"));
					}
					gzin.close();
					bos.close();

					content = sb.toString();
				} else {
					content = bos.toString();
				}

				System.out.println(content);
			} else {
				System.out.println("error code is " + response.getStatusLine().getStatusCode());
			}
			return content;

		} finally {
			if (bis != null) {
				try {
					bis.close();// 最后要关闭BufferedReader
				} catch (Exception e) {
				}
			}
		}
	}
}